package org.sky.axis2.soap;

import java.util.Iterator;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.client.async.AxisCallback;
import org.apache.axis2.context.MessageContext;

public class SoapFaultClient {
	static boolean finish = false;

	public static void main(String[] args) {
		EndpointReference epr = new EndpointReference(
				"http://localhost:8080/Axis2Service/services/SoapFaultService");
		ServiceClient sender = null;
		try {
			OMFactory factory = OMAbstractFactory.getOMFactory();
			OMNamespace ns = factory.createOMNamespace(
					"http://soap.axis2.sky.org", "");
			OMElement request = factory.createOMElement("Price", ns);
			Options options = new Options();
			options.setAction("urn:getPrice");
			options.setTo(epr);
			options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
			options.setUseSeparateListener(true);
			AxisCallback callback = new AxisCallback() {
				public void onMessage(MessageContext msgContext) {
					OMElement result = msgContext.getEnvelope().getBody()
							.getFirstElement();
					OMElement priceElement = result;
					System.out.println("price====" + priceElement.getText());
					finish = true;
				}

				public void onFault(MessageContext msgContext) {
					QName errorCode = new QName("faultcode");
					QName reason = new QName("faultstring");
					// System.out.println("on
					// fault:"+msgContext.getEnvelope().getBody().getFault().toString());
					OMElement fault = msgContext.getEnvelope().getBody()
							.getFault();
					System.out.println("ErrorCode["
							+ fault.getFirstChildWithName(errorCode).getText()
							+ "] caused by: "
							+ fault.getFirstChildWithName(reason).getText());
				}

				public void onError(Exception e) {
				}

				public void onComplete() {
					System.out.println("OnComplete!!!");
				}
			};
			sender = new ServiceClient();
			sender.setOptions(options);
			sender.engageModule("addressing");
			try {

				// sender.sendReceiveNonBlocking(request, callback);
				sender.sendReceiveNonBlocking(null, callback);
			} catch (AxisFault e) {
				System.out.println("Exception occur!");
				System.out.println(e.getMessage());
			}
			synchronized (callback) {
				if (!finish) {
					try {
						callback.wait(1000);
					} catch (Exception e) {
					}
				}
			}
		} catch (AxisFault e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} finally {

			try {
				sender.cleanup();
			} catch (Exception e) {
			}
		}

	}
}